package com.yx.frame.builder;

import java.util.Calendar;
import java.util.List;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.DateTime;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Text;
import com.yx.frame.builder.xml.ServiceBuilderXml;
import com.yx.frame.builder.xml.JavaMethodContentXml;
import com.yx.frame.builder.xml.MethodParmXml;
import com.yx.frame.builder.xml.MethodXml;
import com.yx.frame.builder.xml.QueryMethodContentXml;
import com.yx.frame.builder.xml.UpdateMethodContentXml;

public class MethodPublic extends Composite {
	Shell window = null;
	private Text mId;
	private Text mName;
	private Text mAuthor;
	private Combo mType;
	private Text mComment;
	private Text mPath;
	private DateTime mTime;
	String filePath;
	String methodName;
	Button deleteButton;
	Button saveButton;
	TabItem ParmsTab;
	TabItem SqlsTab;
	TabItem MenCacheTab;
	TabFolder tabFolder;
	ServiceBuilderXml appHelperXml;
	Button removeMemcachedUserLicense;
	Button isMobilApp;
	private Button testMethod;
	private Button asyncService;

	/**
	 * Create the composite.
	 * 
	 * @param parent
	 * @param style
	 */
	public MethodPublic(Composite parent, int style) {
		super(parent, style);
		setLayout(null);
		window = (Shell) parent;
		// this.filePath=filePath;
		// this.methodName=filePath;
		Label label = new Label(this, SWT.NONE);
		label.setBounds(32, 40, 61, 17);
		label.setText("服务编号：");

		mId = new Text(this, SWT.BORDER);
		mId.setToolTipText("不能重号，否则编译出错");
		mId.setBounds(96, 37, 57, 23);

		Label label_1 = new Label(this, SWT.NONE);
		label_1.setBounds(159, 40, 61, 17);
		label_1.setText("方法名称：");

		mName = new Text(this, SWT.BORDER);
		mName.setToolTipText("采用JAVA命名方法，文件内不能重名");
		mName.setBounds(220, 37, 168, 23);
		
		Label label_3 = new Label(this, SWT.NONE);
		label_3.setBounds(394, 40, 48, 17);
		label_3.setText("创建人：");

		mAuthor = new Text(this, SWT.BORDER);
		mAuthor.setBounds(446, 37, 104, 23);

		Label label_4 = new Label(this, SWT.NONE);
		label_4.setText("方法说明：");
		label_4.setBounds(32, 67, 61, 17);

		mComment = new Text(this, SWT.BORDER);
		mComment.setBounds(96, 64, 454, 23);

		Label label_5 = new Label(this, SWT.NONE);
		label_5.setText("日期：");
		label_5.setBounds(556, 67, 32, 17);

		mTime = new DateTime(this, SWT.BORDER);
		mTime.setBounds(595, 63, 88, 24);

		Label label_6 = new Label(this, SWT.SEPARATOR | SWT.HORIZONTAL);
		label_6.setBounds(32, 90, 651, 3);

		tabFolder = new TabFolder(this, SWT.NONE);
		tabFolder.setBounds(32, 98, 651, 442);

		ParmsTab = new TabItem(tabFolder, SWT.NONE);
		ParmsTab.setText("参数声明");

		SqlsTab = new TabItem(tabFolder, SWT.NONE);
		SqlsTab.setText("服务声明");
		MenCacheTab = new TabItem(tabFolder, SWT.NONE);
		MenCacheTab.setText("缓存设置");

		saveButton = new Button(this, SWT.NONE);
		saveButton.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				MessageBox messageBox = new MessageBox(window, SWT.OK
						| SWT.CANCEL);
				messageBox.setMessage("您确定要保存方法：" + mName.getText() + "吗?");
				if (messageBox.open() == SWT.OK) {
					try {
						save();
					} catch (Exception ex) {
						MessageBox messageerrBox = new MessageBox(window,
								SWT.OK);
						messageerrBox.setMessage("保存方法：" + mName.getText()
								+ "出错:" + ex);
						if (messageerrBox.open() == SWT.OK) {
							return;
						} else {
							return;
						}
					}
				}
			}
		});
		saveButton.setBounds(425, 546, 80, 27);
		saveButton.setText("保存");

		deleteButton = new Button(this, SWT.NONE);
		deleteButton.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				if (methodName == null) {
					return;
				}
				MessageBox messageBox = new MessageBox(window, SWT.OK
						| SWT.CANCEL);
				messageBox.setMessage("您确定要删除方法：" + methodName + "吗?");
				if (messageBox.open() == SWT.OK) {
					appHelperXml.removeMethod(methodName);
					try {
						appHelperXml.save();
						((LeftControlTree) window.getChildren()[0])
								.refrashMethodTable(appHelperXml.getFileName(),
										null);
						window.getChildren()[1].setVisible(false);
					} catch (Exception ex) {
						MessageBox messageerrBox = new MessageBox(window,
								SWT.OK);
						messageerrBox.setMessage("删除方法：" + methodName + "出错:"
								+ ex);
						if (messageerrBox.open() == SWT.OK) {
							return;
						} else {
							return;
						}
					}
				}
			}
		});
		deleteButton.setText("删除");
		deleteButton.setBounds(603, 546, 80, 27);

		Label label_7 = new Label(this, SWT.NONE);
		label_7.setBounds(556, 40, 32, 17);
		label_7.setText("类型：");

		mType = new Combo(this, SWT.NONE);
		mType.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				String type = mType.getText().trim();
				if ("query".equals(type)) {
					MethodParms methodParms = (MethodParms) ParmsTab
							.getControl();
					methodParms.setType(type);
					QueryContent queryContent = new QueryContent(tabFolder,
							SWT.NONE, window);
					if (SqlsTab.getControl() != null) {
						SqlsTab.getControl().dispose();
					}
					SqlsTab.setControl(queryContent);
					MenCacheTab.getControl().setEnabled(true);
				} else if ("update".equals(type)) {
					MethodParms methodParms = (MethodParms) ParmsTab
							.getControl();
					methodParms.setType(type);
					UpdateContent updateContent = new UpdateContent(tabFolder,
							SWT.NONE, window);
					if (SqlsTab.getControl() != null) {
						SqlsTab.getControl().dispose();
					}
					SqlsTab.setControl(updateContent);
					((MencacheContent) MenCacheTab.getControl())
							.setUpdateDisnable();
					MenCacheTab.getControl().setEnabled(false);
				} else if ("java".equals(type)) {
					MethodParms methodParms = (MethodParms) ParmsTab
							.getControl();
					methodParms.setType(type);
					JavaContent javaContent = new JavaContent(tabFolder,
							SWT.NONE);
					if (SqlsTab.getControl() != null) {
						SqlsTab.getControl().dispose();
					}
					SqlsTab.setControl(javaContent);
					MenCacheTab.getControl().setEnabled(true);
				} else {
					mType.setText("query");
					MethodParms methodParms = (MethodParms) ParmsTab
							.getControl();
					methodParms.setType(type);
					QueryContent queryContent = new QueryContent(tabFolder,
							SWT.NONE, window);
					if (SqlsTab.getControl() != null) {
						SqlsTab.getControl().dispose();
					}
					SqlsTab.setControl(queryContent);
					MenCacheTab.getControl().setEnabled(true);
				}
			}
		});
		mType.setItems(new String[] { "query", "update", "java" });
		mType.setBounds(595, 36, 88, 25);
		mType.select(0);

		Label label_8 = new Label(this, SWT.SEPARATOR | SWT.HORIZONTAL);
		label_8.setBounds(32, 29, 651, 2);

		Label label_9 = new Label(this, SWT.NONE);
		label_9.setBounds(32, 5, 61, 17);
		label_9.setText("文件路径：");

		mPath = new Text(this, SWT.BORDER);
		mPath.setEditable(false);
		mPath.setBounds(96, 2, 587, 23);

		testMethod = new Button(this, SWT.NONE);
		testMethod.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				if (methodName == null || "".equals(methodName))
					return;
				MethodTest methodTest = new MethodTest(window, SWT.NONE,
						appHelperXml.getMethod(methodName));
				methodTest.open();
			}
		});
		testMethod.setText("测试");
		testMethod.setBounds(514, 546, 80, 27);
		
		removeMemcachedUserLicense = new Button(this, SWT.CHECK);		
		removeMemcachedUserLicense.setBounds(32, 551, 206, 17);
		removeMemcachedUserLicense.setText("服务执行完毕清除本用户权限缓存");
		
		isMobilApp = new Button(this, SWT.CHECK);
		isMobilApp.setBounds(244, 551, 93, 17);
		isMobilApp.setText("用于手机APP");
		
		asyncService = new Button(this, SWT.CHECK);
		asyncService.setText("异步服务");
		asyncService.setBounds(345, 551, 69, 17);

	}

	public void save() throws Exception {
		MethodXml methodXml = new MethodXml();

		int id = -1;
		try {
			id = Integer.parseInt(mId.getText().trim());
			if (id < 0)
				throw new Exception("方法编号不能小于零");
			if (this.methodName == null && appHelperXml.containMehtodId(id)) {
				throw new Exception("新建方法编号在本文件中已经存在，不能重复");
			}
			if (this.methodName != null) {
				MethodXml oldMethodXml = appHelperXml
						.getMethod(this.methodName);
				if (id != oldMethodXml.getId()
						&& appHelperXml.containMehtodId(id)) {
					throw new Exception("编辑方法编号在本文件中已经存在，不能重复");
				}
			}

		} catch (Exception e) {
			throw new Exception("方法编号输入错：" + e);
		}
		methodXml.setId(id);
		String name = mName.getText().trim();
		if ("".equals(name)) {
			throw new Exception("方法名称不能为空");
		}
		if (this.methodName == null && appHelperXml.getMethod(name) != null) {
			throw new Exception("新建方法与文件中的方法重名，不能保存");
		}
		methodXml.setName(name);
		String type = mType.getText().trim();
		if (!"query".equals(type) && !"update".equals(type)
				&& !"java".equals(type)) {
			throw new Exception("方法类型必须是query/update/java三者之一");
		}
		methodXml.setType(type);
		methodXml.setAuthor(mAuthor.getText().trim());
		methodXml.setComment(mComment.getText().trim());
		methodXml.setDate(mTime.getYear() + "-" + (mTime.getMonth()+1) + "-"
				+ mTime.getDay());
		if(removeMemcachedUserLicense.getSelection()){
			methodXml.setRemoveMemcachedUserLicense("true");
		}else{
			methodXml.setRemoveMemcachedUserLicense("false");
		}
		if(isMobilApp.getSelection()){
			methodXml.setIsMobilApp("true");
		}else{
			methodXml.setIsMobilApp("false");
		}
		if(asyncService.getSelection()){
			methodXml.setAsyncService("true");
		}else{
			methodXml.setAsyncService("false");
		}		
		MethodParms methodParms = (MethodParms) ParmsTab.getControl();
		methodXml.copyMethodParms(methodParms.getParms());
		if ("query".equals(methodXml.getType())) {
			QueryContent queryContent = (QueryContent) SqlsTab.getControl();
			if (queryContent.getQueryMethodContentXml().getTransaction().size() < 1) {
				throw new Exception("查询sql不能为空");
			}
			methodXml.setPagination(queryContent.getPagination());
			methodXml.setMethodContentXml(queryContent
					.getQueryMethodContentXml());
		} else if ("update".equals(methodXml.getType())) {
			UpdateContent updateContent = (UpdateContent) SqlsTab.getControl();
			if (updateContent.getUpdateMethodContentXml(methodParms.getParms()).getTransaction()
					.size() < 1) {
				throw new Exception("数据库更新sql不能为空");
			}
			methodXml.setMethodContentXml(updateContent
					.getUpdateMethodContentXml(methodParms.getParms()));			

		} else if ("java".equals(methodXml.getType())) {
			JavaContent javaContent = (JavaContent) SqlsTab.getControl();
			if (javaContent.getJavaMethodContentXml().getClassname().trim()
					.equals("")) {
				throw new Exception("java类名不能为空");
			}
			if (javaContent.getJavaMethodContentXml().getStaticMethodName()
					.trim().equals("")) {
				throw new Exception("java静态方法名不能为空");
			}
			methodXml
					.setMethodContentXml(javaContent.getJavaMethodContentXml());
		}
		MencacheContent mencacheContent = ((MencacheContent) MenCacheTab
				.getControl());
		methodXml.setMethodMencacheXml(mencacheContent.getMethodMencacheXml());
		if (this.methodName == null) {
			appHelperXml.addMethod(methodXml);
		} else {
			appHelperXml.removeMethod(methodName);
			appHelperXml.addMethod(methodXml);
		}
		appHelperXml.save();

		((LeftControlTree) window.getChildren()[0]).refrashMethodTable(
				appHelperXml.getFileName(), methodXml.getName());
		this.methodName = methodXml.getName();
		deleteButton.setEnabled(true);
		saveButton.setText("保存");
		// window.getChildren()[1].setVisible(false);
	}

	public void editMethod(String filePath, String methodName) throws Exception {
		clearMethod();
		this.filePath = filePath;
		this.methodName = methodName;
		appHelperXml = new ServiceBuilderXml(this.filePath);
		mPath.setText(filePath);
		if (methodName != null) {
			mName.setText(methodName);
			mName.setEditable(true);
			mId.setEditable(true);
			mAuthor.setEditable(false);
			mType.setEnabled(false);
			mTime.setEnabled(false);
			

			deleteButton.setEnabled(true);
			saveButton.setText("保存");

			MethodXml methodXml = appHelperXml.getMethod(methodName);
			mId.setText("" + methodXml.getId());
			mName.setText(methodXml.getName());
			mType.setText(methodXml.getType());
			mAuthor.setText(methodXml.getAuthor());
			mComment.setText(methodXml.getComment());

			String[] timeArray = methodXml.getDate().split("-");
			mTime.setYear(Integer.parseInt(timeArray[0]));
			mTime.setMonth(Integer.parseInt(timeArray[1])-1);
			mTime.setDay(Integer.parseInt(timeArray[2]));
			
			if("true".equals(methodXml.getRemoveMemcachedUserLicense())){
				removeMemcachedUserLicense.setSelection(true);
			}else{
				removeMemcachedUserLicense.setSelection(false);
			}
			if("true".equals(methodXml.getIsMobilApp())){
				isMobilApp.setSelection(true);
			}else{
				isMobilApp.setSelection(false);
			}
			if("true".equals(methodXml.getAsyncService())){
				asyncService.setSelection(true);
			}else{
				asyncService.setSelection(false);
			}
			
			MethodParms methodParms = (MethodParms) ParmsTab.getControl();

			if ("query".equals(methodXml.getType())) {
				methodParms.setType(methodXml.getType());
				QueryContent queryContent = new QueryContent(tabFolder,
						SWT.NONE, window);
				if (SqlsTab.getControl() != null) {
					SqlsTab.getControl().dispose();
				}
				SqlsTab.setControl(queryContent);
				QueryMethodContentXml queryMethodContentXml = (QueryMethodContentXml) methodXml
						.getMethodContentXml();
				queryContent.setQueryMethodContentXml(queryMethodContentXml);
				queryContent.setQueryInfo(methodXml.getPagination());

				MenCacheTab.getControl().setEnabled(true);

			} else if ("update".equals(methodXml.getType())) {
				methodParms.setType(methodXml.getType());
				UpdateContent updateContent = new UpdateContent(tabFolder,
						SWT.NONE, window);
				if (SqlsTab.getControl() != null) {
					SqlsTab.getControl().dispose();
				}
				SqlsTab.setControl(updateContent);
				UpdateMethodContentXml updateMethodContentXml = (UpdateMethodContentXml) methodXml
						.getMethodContentXml();
				updateContent.setUpdateMethodContentXml(updateMethodContentXml);
				((MencacheContent) MenCacheTab.getControl())
						.setUpdateDisnable();
				MenCacheTab.getControl().setEnabled(false);

			} else if ("java".equals(methodXml.getType())) {
				methodParms.setType(methodXml.getType());
				JavaContent javaContent = new JavaContent(tabFolder, SWT.NONE);
				if (SqlsTab.getControl() != null) {
					SqlsTab.getControl().dispose();
				}
				SqlsTab.setControl(javaContent);
				JavaMethodContentXml javaMethodContentXml = (JavaMethodContentXml) methodXml
						.getMethodContentXml();
				javaContent.setJavaMethodContentXml(javaMethodContentXml);
				MenCacheTab.getControl().setEnabled(true);
			}

			List<MethodParmXml> parms = methodXml.getMethodParms();
			for (int i = 0; i < parms.size(); i++) {
				MethodParmXml parm = parms.get(i);
				methodParms.addParm(parm.getId(), parm.getName(),
						parm.getType(), parm.getIsMutilist(),
						parm.getSqlIndex(), parm.getValidator(),
						parm.getComment());
			}
			MencacheContent mencacheContent = (MencacheContent) MenCacheTab
					.getControl();
			mencacheContent.setMethodMencacheXml(methodXml
					.getMethodMencacheXml());
		}
	}

	public void clearMethod() {
		mId.setEditable(true);
		mName.setEditable(true);
		mAuthor.setEditable(true);
		mType.setEnabled(true);
		mTime.setEnabled(true);
		mId.setText("");
		mName.setText("");
		mAuthor.setText("");
		mType.select(0);
		mComment.setText("");
		mPath.setText("");
		Calendar date = Calendar.getInstance();
		// mTime.setDate(date.get(Calendar.YEAR),date.get(Calendar.MONTH)+1,date.get(Calendar.DAY_OF_MONTH));
		mTime.setYear(date.get(Calendar.YEAR));
		mTime.setMonth(date.get(Calendar.MONTH) + 1);
		mTime.setDay(date.get(Calendar.DAY_OF_MONTH));
		deleteButton.setEnabled(false);
		saveButton.setText("创建");
		MethodParms methodParms = new MethodParms(tabFolder, SWT.NONE, window,
				SqlsTab, MenCacheTab);
		if (ParmsTab.getControl() != null) {
			ParmsTab.getControl().dispose();
		}
		methodParms.setType("query");
		ParmsTab.setControl(methodParms);
		QueryContent queryContent = new QueryContent(tabFolder, SWT.NONE,
				window);
		if (SqlsTab.getControl() != null) {
			SqlsTab.getControl().dispose();
		}
		SqlsTab.setControl(queryContent);

		MencacheContent mencacheContent = new MencacheContent(tabFolder,
				SWT.NONE);
		if (MenCacheTab.getControl() != null) {
			MenCacheTab.getControl().dispose();
		}
		MenCacheTab.setControl(mencacheContent);
	}

	@Override
	protected void checkSubclass() {
		// Disable the check that prevents subclassing of SWT components
	}
}
